package com.zszedu.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zszedu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

//拦截器，拦截器必须要实现 HandlerInterceptor 接口！！！！！！！！！！！！
@Component //实例化
public class LoginInterceptor implements HandlerInterceptor {
    //如果该每没有进行实例化，则该属性是无法进行自动赋值的
    @Autowired
    private RedisTemplate redisTemplate; //控制Redis对象

    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler) throws java.lang.Exception {
        System.out.println("测试");
        System.out.println("测试");
        System.out.println("测试");
        System.out.println("测试");
        System.out.println("测试");

        //getHeader() : 获取浏览器指定参数信息(标签信息)
        String token = request.getHeader("token");

        //从Redis中获取登录时，存放在Redis缓存中的用户信息
        String key = "login:" + token;
        ValueOperations forValue = redisTemplate.opsForValue();
        User user =(User) forValue.get(key);

        //如果从Redis中获取的数据为空，则用户还没有登录(登录成功时会存储用户数据在Redis中),拦截该请求
        if (user == null){
            System.out.println("测试2");
            System.out.println("测试2");
            System.out.println("测试2");
            System.out.println("测试2");
            System.out.println("测试2");

            Map map = new HashMap(){{
                put("success",false);
                put("msg","还没有进行登录！");
                put("code","777");
            }};
            //通过 ObjectMapper 将 任意对象 转换成字符串
            ObjectMapper mapper = new ObjectMapper();
            String string = mapper.writeValueAsString(map);
            //因为写入的字符串中包含中文所有要设置内容编码集 ！！！！！！！！！！！
            response.setContentType("application/json; charset=UTF-8");
            //将该字符串写入给前端浏览器页面中
            response.getWriter().write(string);


            System.out.println("测试2");
            System.out.println("测试2");
            System.out.println("测试2");
            System.out.println("测试2");
            System.out.println("测试2");
            return false;
        }

        return true;
    }
}
